<template>
    <div id="paramsClass">
        <el-alert
            title="注意：只允许为第三级分类设置相关参数！"
            type="warning"
            show-icon>
        </el-alert>
    <div class="comClass">
        <span>请选择商品分类</span>
        <el-cascader 
        :options="options" 
        :props="{label: 'cat_name',value:'cat_id'}" 
        v-model="value"
        @change="change"
        ></el-cascader>
    </div>
    <el-tabs v-model="activeName" @tab-click="handleClick" class="btn">
        <el-tab-pane label="动态参数" name="first">
            <el-button type="primary" size="mini" :disabled="disabled" @click="dynamic">动态参数</el-button>
        </el-tab-pane>
        <el-tab-pane label="静态参数" name="second">
            <el-button type="primary" size="mini" :disabled="disabled" @click="static">静态属性</el-button>
        </el-tab-pane>
   </el-tabs>
    <el-table :data="parameter" border >
        <el-table-column prop="" label="" width="50" type="expand">
            <template slot-scope="scope">
                <el-tag v-show="many[scope.row.index-1]!=''" v-for="item,i in many[scope.row.index-1]" :key="item.i" closable type="" closable 
                style="margin-left:10px;margin-bottom:10px" @close="closeTag(item,many[scope.row.index-1],scope.row)">
                    {{item}}
                </el-tag>
                <el-input
                    class="input-new-tag"
                    v-if="editTag.inputVisible"
                    v-model="editTag.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(many[scope.row.index-1],scope.row)"
                    @blur="handleInputConfirm(many[scope.row.index-1],scope.row)"
                    >
                </el-input>
                <el-button  class="button-new-tag" size="small" @click="showInput">+ New Tag</el-button>
                </el-input>
            </template>
        </el-table-column>
        <el-table-column prop="index" label="#" width="480"></el-table-column>
        <el-table-column prop="attr_name" label="参数名称" width="480"></el-table-column>
        <el-table-column prop="" label="操作">
            <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="edit(scope.row)"></el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="del(scope.row)"></el-button>
            </template>
        </el-table-column>
    </el-table>
    <el-dialog :title="formName.title" :visible.sync="formName.dialogEdit" width="50%" :before-close="handleClose">
        <el-form ref="form" :model="formName" label-width="80px" :rules="rules">
            <el-form-item :label="formName.header" prop="name">
                <el-input v-model="formName.name"></el-input>
            </el-form-item>
            <el-form-item :label="formName.header2" prop="name" v-show="formName.title=='添加静态属性'">
                <el-input v-model="formName.val"></el-input>
            </el-form-item>
        </el-form>
    <span slot="footer" class="dialog-footer">
        <el-button @click="dialogEdit = false">取 消</el-button>
        <el-button type="primary" @click="sub('form')" >确 定</el-button>
    </span>
    </el-dialog>
    <!--编辑的弹窗-->
    <el-dialog :title="editForm.title" :visible.sync="editForm.dialogVisible" width="30%" :before-close="handleClose">
    <el-form :model="editForm" :rules="rules" ref="editForm" label-width="100px" class="demo-ruleForm">
            <el-form-item :label="editForm.label" prop="name">
                <el-input v-model="editForm.name"></el-input>
            </el-form-item>
    </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="editForm.dialogVisible = false">取 消</el-button>
            <el-button type="primary"  @click="subEdit('editForm')">确 定</el-button>
        </span>
    </el-dialog>
    </div>
</template>

<script>
export default {
     data(){
        return {
          formName:{
                dialogEdit:false,
                name:"",
                title:"添加动态参数",
                header:"动态参数",
                header2:"属性值",
                val:"", //属性值
               
                },
            editForm:{
                name:"",
                dialogVisible:false,
                title:"修改动态参数",
                label:"动态属性",
                attr_id:"",
                cat_id:"",
                attr_sel:""
            },
            editTag:{
                 inputVisible: false,
                inputValue: ""
            },
            options:[],
             activeName: 'first',
             value:[],
             disabled:true,
             parameter:[], //参数列表
             many:[],//参数集合
             only:"", //静态属性
             movement:"many" ,//一开始设置默认为many,
            rules: {
            name: [
                { required: true, message: '请输入内容', trigger: 'blur' },
               
            ],
            val1:[
                { required: true, message: '请输入内容', trigger: 'blur' },
               
            ],
          }
        }  
    },
    methods:{
        //获取商品数据
       getData(){
            this.$http.get("categories",{headers:{"Authorization":localStorage.getItem("token")}}).then(res=>{
               // console.log(res.body)
                this.options = res.body.data;
            })
        },
        handleClick(tab, event) {
            if(tab.index == 0){
                this.movement="many"
                this.editForm.title="修改动态参数"
                this.editForm.label="动态参数"
                this.getParms()
            }
            else if(tab.index == 1){
                this.movement="only"
                this.editForm.title="修改静态参数"
                this.editForm.label="静态参数"
                this.getParms()
            }
        },
        //获取动态参数和静态属性
      getParms(){
           this.$http.get("categories/"+this.value+"/attributes",
           {params:{sel:this.movement},
           headers:{"Authorization":localStorage.getItem("token")}})
          .then(res=>{
              if(res.body.meta.status == 200){
                   this.parameter = res.body.data
                    this.parameter.forEach((item,i)=>{
                        item.index = i+1
                    })
                   if(this.movement == "many"){
                       this.many=[];
                       let arr = [];
                       if(res.body.data.length){
                         let many= res.body.data[0].attr_vals 
                         arr = many.split(",")
                        this.many.push(arr)  //将数据都统一处理为二维数组的格式方便渲染
                       }
                     }
                    else if(this.movement == "only"){
                        this.many=[];
                        let arr = []
                        this.parameter.forEach((item,i)=>{
                           arr[i]=item.attr_vals
                          })
                        arr.forEach(item=>{
                           let only = item.split(" ")
                           // console.log(only)
                            this.many.push(only) 
                        })
                    }
                   // console.log(this.parameter)
                }
           })
      },
      //动态参数弹窗
      dynamic(){
            this.formName.title = "添加动态参数"
            this.formName.header="动态参数"
            this.formName.dialogEdit = true
         },
      //静态属性弹窗
      static(){
           this.formName.dialogEdit = true
           this.formName.title = "添加静态属性"
           this.formName.header="静态属性"
      },
      //添加动态参数
      sub(){
           this.$refs.form.validate((valid) => {
                if (valid) {
                this.formName.dialogEdit = false
                    this.$http.post("categories/"+this.value+"/attributes",
                    { attr_sel:this.movement,attr_name:this.formName.name,attr_vals:this.formName.val },
                    { headers:{"Authorization":localStorage.getItem("token")} }
                    )
                    .then(res=>{
                        if(res.body.meta.status == 201){
                            let data = res.body.data
                            this.getParms()
                            this.parameter.forEach((item,i)=>{
                                item.index = i+1
                            })
                            this.formName.name = ""
                            this.$message({
                                message: '添加成功',
                                type: 'success'
                            });
                        }
                        else{
                            this.$message.error('添加失败');
                        }
                    })
                } 
                else {
                    return false;
                }
            });
        },
     //编辑
       edit(row){
          this.editForm.dialogVisible = true
          this.editForm.cat_id = row.cat_id
          this.editForm.attr_id = row.attr_id
          this.editForm.name = row.attr_name
          this.editForm.attr_sel = row.attr_sel
         // console.log(row)
       },
       //提交编辑
       subEdit(){
            this.$refs.editForm.validate((valid) => {
                if (valid) {
                this.editForm.dialogVisible = false
                this.$http.put("categories/"+this.editForm.cat_id+"/attributes/"+this.editForm.attr_id,
                            { attr_sel:this.editForm.attr_sel,attr_name:this.editForm.name },
                            { headers:{"Authorization":localStorage.getItem("token")} })
                .then(res=>{
                    if(res.body.meta.status == 200){
                         this.$message({
                            message: '修改成功',
                            type: 'success'
                            });
                             this.getParms()
                         }
                    else{
                        this.$message.error('修改失败');
                     }
                })
            } 
            else {
                return false;
                }
            });
       },
       //删除
       del(row){
         this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
           this.$http.delete("categories/"+row.cat_id+"/attributes/"+row.attr_id,
           { headers:{"Authorization":localStorage.getItem("token")} })
           .then(res=>{
               if(res.body.meta.status == 200){
                    this.getParms()
                     this.$message({
                    message: '删除成功',
                    type: 'success'
                });
              }
            })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
          
       },
      change(value){
          this.value = value[2];
          this.disabled = false
          this.getParms()
        },
        handleClose(done) {
            this.$confirm('确认关闭？')
            .then(_ => {
                done();
            })
            .catch(_ => {});
        },
        showInput() {
            this.editTag.inputVisible = true;
            this.$nextTick(_ => {
                this.$refs.saveTagInput.$refs.input.focus();
            });
        },
        handleInputConfirm(dynamicTags,row) {
           // console.log(row)
        let inputValue = this.editTag.inputValue;
        if (inputValue) {
          dynamicTags.push(inputValue);
           if(dynamicTags[0]==""){
            dynamicTags.splice(0,1)
         }
          let attr = dynamicTags.join(",")
          //console.log(attr)
          this.$http.put("categories/"+row.cat_id+"/attributes/"+row.attr_id,{attr_name:row.attr_name,attr_sel:row.attr_sel,attr_vals:attr},
          { headers:{"Authorization":localStorage.getItem("token")} }
            )
            .then(res=>{
                console.log(res.body)
            })
        }
        this.editTag.inputVisible = false;
        this.editTag.inputValue = '';
      },
        closeTag(tag,dynamicTags,row) {
            //console.log(row)
            this.$http.delete("categories/"+row.cat_id+"/attributes/"+row.attr_id,{headers:{"Authorization":localStorage.getItem("token")}})
            .then(res=>{
                if(res.body.meta.status ==200){
                        this.$message({
                        message: '删除成功',
                        type: 'success'
                    })
                }
               // console.log(res.body)
            })
           dynamicTags.splice(dynamicTags.indexOf(tag), 1);
          
      },
    },
    created(){
        this.$store.commit("changeTitle",{"t1":"商品管理","t2":"商品分类"})
        this.getData()
    }
}
</script>

<style lang="scss" scoped>
    #paramsClass{
        .comClass{
            margin:20px 0
        }
        .btn{
            margin-bottom: 20px
        }
        .input-new-tag{
            width: 90px;
            position: absolute
        }
    }
</style>